export default {
  data() {
    return {
      parentNav: {},
      apiNavList: []
    }
  },

  methods: {
    genTree () {
      for (const nav of this.apiNavList) {
        const navChildren = this.apiNavList.filter(item => item.parentId === nav.pageId)

        if (this.subMenuVisibal) {
          if (navChildren.length > 0) {
            nav.children = navChildren
          }
        }
      }

      this.apiNavList = this.apiNavList.filter(item => item.parentId === (this.parentId || '0'))
    },

    genNav (item) {
      return {
        ...item,
        id: item.pageId,
        roles: item.roles ? item.roles.split(',') : [],
        order: item.order,
        pageId: item.pageId,
        activeText: item.pageId,
        parentId: item.parentId,
        target: item.target || (item.pageType === '4' ? '_blank' : '_self'),
        name: item.navigateName || item.name,
        href: item.href || `./${item.fileName}.html`
      }
    },

    async getNavigationFromPage () {
      this.apiNavList = []

      if (this.parentId && this.parentId !== '0') {
        this.parentNav = {}

        await window.axios.post(`${window.$twApp.gateway}/unified-portal/site/query/page`, {
          // siteId: 'r4BYUj40gGUg',
          siteId: this.$siteConfig ? this.$siteConfig.siteId : '',
          showInNavigate: '1',
          pageId: this.parentId
        }).then((response) => {
          if (response.data.result && response.data.result.length > 0) {
            this.parentNav = this.genNav(response.data.result[0])
          }
        })
      }

      window.axios.post(`${window.$twApp.gateway}/unified-portal/site/query/page`, {
        // siteId: 'cF5j8CgLY3X7',
        siteId: this.$siteConfig ? this.$siteConfig.siteId : '',
        showInNavigate: '1',
        parentId: this.parentId
      }).then((response) => {
        if (response.data.result && response.data.result.length > 0) {
          this.apiNavList = response.data.result.map(item => {
            return this.genNav(item)
          })

          this.apiNavList.sort((a, b) => a.order - b.order)

          this.genTree()
        }
      })
    }
  },

  mounted () {
    this.$root.$on('loaded', this.getNavigationFromPage)
  },

  watch: {
    dataIsFromPortal (val) {
      if (val) {
        this.getNavigationFromPage()
      }
    },

    subMenuVisibal () {
      this.getNavigationFromPage()
    }
  }
}
